<template>
  <lay-table :page="page" :resize="true" :height="tableHeight" :columns="columns" :loading="loading"
    @row-double="handleDialogValue(row.id)" :default-toolbar="defaultToolbars" :data-source="dataSource"
    v-model:selected-keys="selectedKeys" @sortChange="sortChange" even style="height: 100%;">
    <template v-slot:toolbar>
      <!-- 数据筛选 -->
      <lay-form :model="queryForm" ref="addTreeSpeciesForm" isLabelTooltip>
        <lay-form-item mode="inline">
          <lay-button size="xs" type="primary" @click="handleDialogValue(null)">
            <lay-icon type="layui-icon-addition"></lay-icon> 新增
          </lay-button>
          <lay-popconfirm content="确定要删除所选数据吗？确认后将无法恢复！" trigger="click" position="bottom" @confirm="remove"
            @cancel="() => layer.msg('操作已取消！', { icon: 3, time: 1000 })">
            <lay-button size="xs" border="red" border-style="dashed">删除</lay-button>
          </lay-popconfirm>
        </lay-form-item>

        <lay-form-item prop="city" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="queryForm.city" multiple showSearch allow-clear minCollapsedNum=1 placeholder="市"
            size="xs">
            <lay-select-option v-for="city in selectList.cityList" :key="city" :value="city"
              :label="city"></lay-select-option>
          </lay-select>
        </lay-form-item>
        <lay-form-item prop="county" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="queryForm.county" multiple showSearch allow-clear minCollapsedNum=1 placeholder="区/县"
            size="xs">
            <lay-select-option v-for="county in selectList.countyList" :key="county" :value="county"
              :label="county"></lay-select-option>
          </lay-select>
        </lay-form-item>
        <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="queryForm.town" multiple showSearch allow-clear minCollapsedNum=1 placeholder="乡/镇"
            size="xs">
            <lay-select-option v-for="town in selectList.townList" :key="town" :value="town"
              :label="town"></lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="queryForm.forestClass" multiple showSearch allow-clear minCollapsedNum=1
            placeholder="森林类别" size="xs">
            <lay-select-option v-for="value in selectList.forestClassList" :key="value.id" :value="value"
              :label="value"></lay-select-option>
          </lay-select>
        </lay-form-item>
        <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="queryForm.ecologicalZone" multiple showSearch allow-clear minCollapsedNum=1
            placeholder="生态分区" size="xs">
            <lay-select-option v-for="value in selectList.ecologicalZoneList" :key="value.id" :value="value"
              :label="value"></lay-select-option>
          </lay-select>
        </lay-form-item>
      </lay-form>
    </template>
    <template v-slot:operator="{ row }">
      <lay-button size="xs" @click="handleDialogValue(row.id)" type="primary">编辑</lay-button>
      <lay-button size="xs" title="查看">查看</lay-button>
    </template>
  </lay-table>
  <Dialog v-model="dialogVisible" :dialogVisible="dialogVisible" :id="id" :dialogTitle="dialogTitle"
    @initDataList="initDataList"></Dialog>

</template>

<script setup>
import { ref, toRefs, watch, reactive, onMounted, h, computed } from 'vue';
import { layer } from '@layui/layui-vue';
import api from '@/api';
import ImpportResource from '@/views/resource/components/ImpportResource.vue';
import Dialog from './components/dialog.vue'

const queryForm = ref({
  pageNum: 1,
  pageSize: 20,
  province: ["广西"],
  city: [],
  county: [],
  town: [],
  village: [],
  forestClass: [],
  ecologicalZone: []
})

const loading = ref(true);
const selectedKeys = ref([]);

const dataSource = ref([]);
const page = reactive({ current: 1, limit: 20, limits: [20, 50, 100, 500], total: dataSource.value.length, layout: ["page", "limits", "prev", "refresh", "count", "next", "skip",] });
// 分页、排序、筛选等参数
const change = (page) => {
  queryForm.value.pageNum = page.current;
  queryForm.value.pageSize = page.limit;
  loading.value = true;
  initDataList();
}
// attach change handler to page prop per layui-vue new API
page.change = change;

// 计算表格高度
const tableHeight = computed(() => {
  return window.innerHeight - 115 + 'px'
})

// 新增、编辑 dialog
const id = ref(-1)
const dialogVisible = ref(false)
const dialogTitle = ref('')

const handleDialogValue = (resourceId) => {
  if (resourceId) {
    id.value = resourceId;
    dialogTitle.value = "修改数据"
  } else {
    id.value = -1;
    dialogTitle.value = "添加数据"
  }
  dialogVisible.value = true
}

const columns = ref([
  { title: "选项", type: "checkbox", fixed: "left", width: '10px' },
  { title: "ID", key: "id", fixed: "left", align: 'center', width: '20px', hide: true, },
  { title: "年度", key: "year", fixed: "left", align: 'center', hide: true, width: '10px', },
  { title: "省/自治区", key: "province", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "市", key: "city", align: 'center', ellipsisTooltip: true },
  { title: "区/县", key: "county", align: 'center', hide: false, ellipsisTooltip: true, },
  { title: "乡/镇", key: "town", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "村", key: "village", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "植被生态区", key: "vegetation_ecological_zone_name", align: 'center', ellipsisTooltip: true, },
  { title: "生态工程区", key: "ecological_engineering_zone_name", align: 'center', ellipsisTooltip: true, },
  { title: "生态分区", key: "ecological_zone_name", align: 'center' },
  { title: "森林类别", key: "forest_class_name", align: 'center' },
  { title: "事权级", key: "forest_class_level", align: 'center' },
  { title: "生态分区2", key: "ecological_zone_2", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "优势树种", key: "dominant_tree_species_name", align: 'center', ellipsisTooltip: true, },
  { title: "起源", key: "origin_name", align: 'center' },
  { title: "年龄组", key: "age_group_name", align: 'center' },
  { title: "面积(ha)", key: "area", align: 'center', },
  { title: "蓄积(m³)", key: "stock", align: 'center', },
  { title: "蓄积(m³/ha)", key: "stock_per_ha", align: 'center' },
  { title: "平均树高(m)", key: "mean_tree_height", align: 'center' },
  { title: "平均胸径(cm)", key: "mean_dbh", align: 'center' },
  { title: "林分生物量", key: "forest_stand_biomass", align: 'center', },
  { title: "系数", key: "coefficient", align: 'center' },
  { title: "备注", key: "remark", ellipsisTooltip: true, hide: true, },
  { title: "操作", width: "100px", align: 'center', customSlot: "operator", key: "operator", fixed: "right", ignoreExport: true }
]);

const defaultToolbars = [
  "filter",
  {
    icon: "layui-icon-add-one",
    title: "导入",
    onClick: () => {
      layer.drawer({
        title: "批量导入数据",
        content: h(ImpportResource),
        area: ['100%', ''],
        offset: "t",
        resize: true,
        close: () => {
          loading.value = true
          initDataList().then(() => {
            loading.value = false
          })
        }
      })
      console.log("导入数据")
    }
  },
  {
    icon: "layui-icon-refresh",
    title: "刷新",
    onClick: () => {
      loading.value = true;
      initDataList();
    }
  },
  "export",
]

const sortChange = (key, sort) => {
  layer.msg(`字段${key} - 排序${sort}, 你可以利用 sort-change 实现服务端排序`)
}

// 下拉选择列表
const selectList = ref([])
const getSelectList = async () => {
  await api.post('resource/select', queryForm.value).then((res) => {
    if (res.code == 200) {
      console.log('@resource/select res', res)
      selectList.value = res.data
      console.log('@selectList.value', selectList.value)
    } else {
      layer.msg(res.msg, { icon: 2, time: 5000 });
    }
  })
}

// 获取数据列表
const initDataList = async () => {
  loading.value = true
  await api.post("resource/search", queryForm.value).then((res) => {
    if (res.code === 200) {
      loading.value = false
      dataSource.value = res.data || []
      page.total = res.total;
      if (page.total > 500 && !page.limits.includes(page.total)) {
        page.limits.push(page.total);
      }
      getSelectList()
    } else {
      layer.msg(res.msg, { icon: 2, time: 5000 });
    }
  })
}

// 监听筛选条件变化
watch([
  () => queryForm.value.city,
  () => queryForm.value.county,
  () => queryForm.value.town,
  () => queryForm.value.forestClass,
  () => queryForm.value.ecologicalZone,
], () => {
  loading.value = true;
  initDataList();
})

// 删除资源
async function remove() {
  if (selectedKeys.value.length === 0) {
    layer.msg("请选择要删除的资源！", { icon: 2 });
    return;
  } else {
    loading.value = true
    let success_res = []
    let error_res = []
    for (let id of selectedKeys.value) {
      await api.get('resource/delete', { id: id }).then((response) => {
        if (response.code === 200) {
          success_res.push(id)
        } else {
          error_res.push(id)
        }
      });

    }
    initDataList();; // 刷新资源列表
    selectedKeys.value = [];
    loading.value = false
    if (error_res.length) {
      layer.notify({
        title: "Error",
        content: error_res.length + ' 个资源删除失败！\n',
        icon: 2,
        time: 5000,
        offset: 'lt',
      })
    }
  }
}

onMounted(() => {
  initDataList();
});

</script>
<style scoped>
::v-deep .layui-tag-input {
  height: 22px;
}

::v-deep .layui-form-item {
  margin-bottom: 0px;
}
</style>